<script setup>
import { ref, reactive, onMounted, watch, h } from 'vue';
import { fileApi } from '@T2/service/api.ts';
import { ElMessage, ElMessageBox } from 'element-plus';
import { api } from '@T2/plugins/env-config.ts';

const props = defineProps({
  files_json: {
    type: Array,
    required: true,
  },
  updateTimes: {
    type: Number,
    required: true,
  },
  maxSizeMB: {
    type: Number,
    default: 5,
  }
});
const emits = defineEmits(['files-change']);

const Resd = reactive({
  fileList: [],
  canShowRemoveDialog: true,/* 删除弹窗标志，上传不符合格式的文件会触发beforeRemove，此时不弹窗 */
  previewUrl: '',
  previewVisible: false,
});
onMounted(() => {
  initFileList();
});
watch(() => props.updateTimes, (nv, ov) => {
  initFileList();
});
const initFileList = () => {
  Resd.fileList = [];
  props.files_json?.forEach(item => {
    Resd.fileList.push({
      _id: item.id,/* 标志，图片的id，作用为添加了一个图片之后 */
      name: item.name,
      url: `${ api + item.file_url }`,
    })
  });
}
const handleBeforeUpload = (file) => {
  const isImage = file.type.startsWith('image/'); // 检查文件类型是否为图片
  if (!isImage) {
    ElMessage.error('只能上传图片文件！');
    Resd.canShowRemoveDialog = false; // 禁止显示删除弹窗
    return false;
  }
  const isLtMaxSize = file.size / 1024 / 1024 < props.maxSizeMB; // 检查文件大小是否小于maxSizeMB
  if (!isLtMaxSize) {
    ElMessage.error(`文件大小不能超过 ${ props.maxSizeMB }MB！`);
    Resd.canShowRemoveDialog = false; // 禁止显示删除弹窗
    return false;
  }
  return true; // 返回 true 表示允许上传，返回 false 表示禁止上传
}
const handleFileUpload = (option) => {
  let formData  = new FormData();
  formData.append('file', option.file);
  formData.append('ftype', '图片');
  formData.append('name', option.file.name);
  fileApi({
    method: 'post',
    data: formData,
  }).then(res => {
    option.onSuccess(res, option.file);
  }).catch(error => {
    option.onError(error);
  });
}
const handleSuccess = (response, file, fileList) => {
  const index = Resd.fileList.findIndex((item) => item.uid === file.uid);
  if (index !== -1) {
    /* 标志，作用为删除时同时将MainForm.model.files的对应id删除 */
    Resd.fileList[index]._id = response.id;
  }
  const ids = Resd.fileList.map(i => i._id);
  emits('files-change', ids);
}
const handlePreview = (file) => {
  Resd.previewUrl = file.url || file.rawUrl;
  Resd.previewVisible = true;
}
const beforeRemove = (uploadFile, uploadFiles) => {
  if (Resd.canShowRemoveDialog) {
    return ElMessageBox.confirm('', {
      message: h('div', null, [
        h('p',{ style:'font-size:16px;color: #4C4C4C;font-weight:500;'}, `移除图片 ${ uploadFile.name } ?`),
        h('p',{ style:'font-size:14px;color: #9D9D9D;margin:10px 0;' }, '确认后不会立即移除，需再次确认弹窗才会移除。'),
      ]),
      type: 'warning',
      confirmButtonText: '确认',
    }).then(
      () => true,
      () => false
    )
  } else {
    Resd.canShowRemoveDialog = true;/* 重置状态 */
    return true;
  }
}
const handleRemove = (file, uploadFiles) => {
  const ids = Resd.fileList.map(i => i._id);
  emits('files-change', ids);
}
</script>

<template>
  <div class="box">
    <el-upload
      class="upload-demo"
      v-model:file-list="Resd.fileList"
      multiple
      accept="image/*"
      :before-upload="handleBeforeUpload"
      :http-request="handleFileUpload"
      :on-success="handleSuccess"
      list-type="picture-card"
      :on-preview="handlePreview"
      :before-remove="beforeRemove"
      :on-remove="handleRemove"
    >
      <div class="flex--center flex-column plus-name">
        <el-icon color="#0079FE"><Plus /></el-icon>
        选择图片
      </div>
    </el-upload>
    
    <el-dialog v-model="Resd.previewVisible" width="700px">
      <img w-full :src="Resd.previewUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.box {
  display: block;
  width: 100%;
  .plus-name {
    color: #0079FE;
    transform: translateY(10px);
  }
}
</style>

<style scoped>
:deep(.el-dialog .el-dialog__body) {
  display: flex;
  width: 100%;
  height: 700px;
  justify-content: center;
  align-items: center;
}
:deep(.el-dialog .el-dialog__body img) {
  max-width: 100%;
  max-height: 100%;
}
:deep(.el-icon.el-icon--close) {
  display: none !important;
}
:deep(.el-icon--close-tip) {
  display: none !important;
}
:deep(.el-upload.el-upload--picture-card) {
  background-color: #F1F6FF;
}
:deep(.upload-demo .el-upload-list) {
  display: flex;
  flex-wrap: wrap;
}
:deep(.upload-demo .el-upload-list__item),
:deep(.upload-demo .el-upload--picture-card) {
  width: 100px;
  height: 100px;
  margin-right: 10px;
  margin-bottom: 6px;
  position: relative;
  overflow: hidden;
}
:deep(.upload-demo .el-upload-list__item img) {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
</style>